package org.yysd.example;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class KeyValueList2 extends JFrame {
    private DefaultTableModel model;
    private JTable table;
    private JTextField keyField;
    private JTextField valueField;

    public KeyValueList2() {
        super("Key-Value List");

        // 创建表格模型
        model = new DefaultTableModel();
        model.addColumn("Key");
        model.addColumn("Value");

        // 创建表格并使用模型
        table = new JTable(model);

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 创建键和值输入框
        keyField = new JTextField(10);
        valueField = new JTextField(10);

        // 创建添加按钮
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String key = keyField.getText();
                String value = valueField.getText();

                if (!key.isEmpty() && !value.isEmpty()) {
                    model.addRow(new Object[]{key, value});
                    keyField.setText("");
                    valueField.setText("");
                }
            }
        });

        // 创建删除按钮
        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    model.removeRow(selectedRow);
                }
            }
        });

        // 创建底部面板，并添加键、值输入框和按钮
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JLabel("Key:"));
        bottomPanel.add(keyField);
        bottomPanel.add(new JLabel("Value:"));
        bottomPanel.add(valueField);
        bottomPanel.add(addButton);
        bottomPanel.add(deleteButton);

        // 将底部面板添加到窗口
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new KeyValueList2();
            }
        });
    }
}
